import java.util.Random;

public class BinarySeachTree {

    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public static TreeNode root;

    public static void insert(int val){
        if(root == null){
            root = new TreeNode(val);
            return;
        }

        TreeNode node = new TreeNode(val);
        TreeNode cur = root;
        TreeNode parent = root;
        while (cur != null){
            if(cur.val > val){
                parent = cur;
                cur = cur.left;
            }else if(cur.val < val){
                parent = cur;
                cur = cur.right;
            }
        }

        if(parent.val > val) {
            parent.left = node;
        }else {
            parent.right = node;
        }
    }

    public static TreeNode Seach(int val){
        if(root == null){
            return null;
        }
        TreeNode cur = root;
        while (cur != null){
            if(cur.val > val){
                cur = cur.left;
            }else if(cur.val == val){
                return cur;
            }else {
                cur = cur.right;
            }
        }
        return null;
    }

    public static void remove(int val){
        if(root == null){
            return;
        }

        TreeNode cur = root;
        TreeNode parent = root;
        while (cur != null){
            if(cur.val > val){
                parent = cur;
                cur = cur.left;
            }else if(cur.val < val){
                parent = cur;
                cur = cur.right;
            }else {
                break;
            }
        }
        removeNode(cur,parent);
    }

    public static void removeNode(TreeNode cur,TreeNode parent){

        if(cur.left == null){
            if(cur == root){
                root = cur.right;
            }else if(parent.left == cur){
                parent.left = cur.right;
            }else if(parent.right == cur){
                parent.right = cur.right;
            }

        } else if (cur.right == null) {
            if(cur == root){
                root = cur.left;
            }else if(parent.left == cur){
                parent.left = cur.left;
            }else if(parent.right == cur){
                parent.right = cur.left;
            }

        }else {
            TreeNode target = cur.right;
            TreeNode targetParent = cur;
            while (target.left != null){
                targetParent = target;
                target = target.left;
            }

            cur.val = target.val;

            if(target == targetParent.right){
                targetParent.right = target.right;
            }else {
                targetParent.left = target.right;
            }
        }
    }

}
